<?php

/**
 * 登录限制
 * @author zlj <389843954@qq.com>
 */
namespace app\common\model;
use app\common\model\Redis;
use app\common\model\Dev_info;
use app\common\model\Devs_share;
use think\Model;
class Alarm_info extends Model
{
	/**
	 * 获取单条信息
	 * @param  [array] $where [数组]
	 * @return [type]        [description]
	 */
	public function getOne($where,$field='*'){
        $result = self::field($field)->where($where)->find();
        if($result){
            $result = $result->getData();
        }
        return $result;
	}

	/**
     * 从mysql中载入设备的所有报警通知地址到redis
     * @param sting $dev_id 设备号
     * @return void
     * */
    public function addrToRedis($dev_id){
        
        $res = self::field('u_id,addr')->where(array('guid1' => $dev_id, 'valid' => 'Y'))->select();
        
        if($res){
        	$redis = new Redis();
        	$select = $redis->whereRedis($dev_id);
        	if(FALSE === $select) return FALSE;

        	$res = json_decode(json_encode($res),true);

        	$redis->select($select);
	        foreach ($res as $v){
	            $data[$v['u_id']] = $v['addr'];
	        }
	        $redis->hset($dev_id, 'inform_addr', json_encode($data));
        }
    }

    /**
     * array(2) {
     *    [29]=>
     *     string(99) "{"app":"29","sms":"15308016102","email":"389843954@qq.com","weixin":"ojM70wGg15zCctbLDQIJku3uwKes"}"
     *    [70]=>
     *     string(79) "{"app":"70","email":"961313085@qq.com","weixin":"ojM70wBreLxwAT-pQ612BvjMqt4Y"}"
     * }
     * 从redis中获得该设备的所有通知地址
     * @param string $dev_id 设备号
     * @return mixed
     */
    public function getRedisAddr($dev_id){
        $redis = new Redis();
        
        $select = $redis->whereRedis($dev_id);
        if(FALSE === $select) return FALSE;
        $redis->select($select);
        
        $temp = json_decode($redis->hget($dev_id, 'inform_addr'), true);
        
        if($temp){
            foreach ($temp as &$v){
                $v = json_decode($v, true);
            }
            unset($v);
            return $temp;
        }else{
            return false;
        }
    }

    /**
     * 删除一个旧的uid对应记录，再增加一个新uid的记录
     * @param sring $dev_id 设备号
     * @param int $oid 删除的uid
     * @param int $nid 增加的uid
     * @return boolean
     */
    public function delAddAddr($dev_id, $oid, $nid){
        //从mysql、redis中删除$oid的通知地址
        $this->delAddr($dev_id, $oid);
        
        //在mysql、redis中添加新的通知地址
        $this->addAlarmAdr($dev_id, $nid);
    }

    /**
     * 初始化单个设备所有人警报地址，从usr表生成通知地址，载入alram_info,重新载入redis
     * @param string $dev_id
     * @return mix 
     */
    public function initOneDevAddr($dev_id){
        $this->delAllAddr($dev_id);
        $devModel = new Dev_info();
        $uid = $devModel->getOne(['guid1'=>$guid1],'owner');
        if($uid["owner"] && ($uid["owner"] != -1)){
            //重新加载到mysql、redis
            //加载设备拥有人地址
            $this->addAlarmAdrMysql($dev_id, $uid['owner']);
            
            //加载设备共享人地址
            $shareModel = new Devs_share();
            $res = $shareModel->field(array('share_with'))->where(array('guid1' => $dev_id, 'owner_id' => $uid['owner']))->select();
            $res = $shareModel->getAll(['guid1'=>$dev_id,'owner_id'],'share_with');
            if($res){
                $res = json_decode(json_encode($res),true);
            }else{
                return false;
            }
            foreach ($res as $v){
                $this->addAlarmAdrMysql($dev_id, $v['share_with']);
            } 
            
            //从mysql中载入到redis
            $this->addrToRedis($dev_id);
        }else{
            return false;
        }
    }
    
    /**
     * 删除单个设备所有人的mysql警报通知地址，从alarm_info表中删除
     * @param string $dev_id
     * @return void
     * */
    public function delOneDevMysqlAddr($dev_id){
        self::where(array('guid1' => $dev_id))->delete();
    }
    
    
    /**
     * 删除单个设备所有人的redis警报通知地址
     * @param string $dev_id
     * @return void
     * */
    public function delOneDevRedisAddr($dev_id){
        $redis = new Redis();

        $select = $redis->whereRedis($dev_id);
        if($select === false){
            return false;
        } 
        $redis->select($select);
        $redis->hset($dev_id, 'inform_addr', '');
    }
    
    /**
     * 从mysql、redis中删除设备的单条报警通知地址
     * @param string $dev_id 设备号
     * @param int $uid 删除的uid
     * @return void 
     * */
    public function delAddr($dev_id, $uid){
        //mysql中删除$oid的通知地址
        self::where(['guid1'=>$dev_id,'u_id' => $uid])->delete();
        
        //从redis中删除已存在的通知地址
        $redis = new Redis();
        $select = $redis->whereRedis($dev_id);
        if(false === $select){
            return true;
        } 
        $redis->select($select);
        $adr = json_decode($redis->hget($dev_id, 'inform_addr'), true);
        unset($adr[$uid]);
        $redis->hset($dev_id, 'inform_addr', json_encode($adr));
    }
    
    /**
     * 从mysql、redis中删除设备的所有报警通知地址
     * @param string $dev_id 设备号
     * @return void
     */
    public function delAllAddr($dev_id){
        //删除mysql地址
        $this->delOneDevMysqlAddr($dev_id);
        //删除redis地址
        $this->delOneDevRedisAddr($dev_id);
    }
    
  
    /**
     * 修改redis警报推送方式
     * @param int $uid 用户uid
     * @return void
     */
    public function changeRedisAlarmType($uid){
        $rows = self::where(['u_id'=>$uid])->field('guid1,u_id')->select();
        if(!$rows){
            return false;
        }
        $rows = json_decode(json_encode($rows),true);
        foreach ($rows as $v){
            $this->addAlarmAdr($v['guid1'], $uid);
        }
    }
    
    /**
     * 修改redis警报上传次数及间隔时间
     * @param string $dev_id 设备号
     * @param string $num 次数
     * @param string $intv 间隔时间
     * @return void
     * */
    public function ModifyAlarmSetting($dev_id, $num, $intv) {
        $redis = new Redis();
        $select = $redis->whereRedis($dev_id);
        
        if(false === $select){
            return false;
        }
        
        $redis->select($select);
        $redis->hset($dev_id, 'alarm_send_num', $num);
        $res = $redis->hset($dev_id, 'alarm_intv', $intv);

        return true;
    }
    
    /**
     * 修改警报上传次数及间隔时间
     * @param string $dev_id 设备号
     * @param string $num 次数
     * @param string $intv 间隔时间
     * @return void
     * */
    public function getAlarmSetting($dev_id, $uid) {
        $redis = new Redis();
        $select = $redis->whereRedis($dev_id);
        //若redis中存在则从redis中取，redis 不存在从msyql中取
        if(FALSE !== $select){
            $redis->select($select);
            $data['alarm_send_num'] = $redis->hget($dev_id, 'alarm_send_num');
            $data['intv'] = $redis->hget($dev_id, 'alarm_intv');
            
            return $data;
        }else{
            $res = $this->getOne(['guid1'=>$dev_id,'u_id'=>$uid],'times_to_send alarm_send_num,intv');
            $res['intv'] /= 60;
            return $res;
        }
    }
    
    
    /**
     * 设置设备mysql间隔时间和推送次数
     * */
    public function devIntvTimeSeting($dev_id, $uid, $save) {
        $res = self::where(['dev_id' => $dev_id, 'u_id' => $uid])->save($save);
        if($res){
            return true;
        }else{
            return false;
        }

    }
    
    /**
     * 将uid用户的报警通知地址加入到mysql中
     * @param [string] $dev_id
     * @param [int] $uid
     * @return mixed 请用全等判断
     */
    public function addAlarmAdrMysql($dev_id, $uid) {
        $userModel = new User();
        $adr = $userModel->produceUserAddr($uid, $dev_id);
        //先删除一次在添加
        self::where(['guid1'=>$dev_id,'u_id'=>$uid])->delete();

        $res=self::add(['guid1'=>$dev_id,'u_id'=>$uid,'addr'=>json_encode($adr)]);
        
        if($res){
            return $adr;
        }else{
            return FALSE;
        }
    }
    
    /**
     * 将uid用户的报警通知地址加入到mysql和redis中
     * @param string $dev_id
     * @param int $uid
     * @return mixed 
     * */
    public function addAlarmAdr($dev_id, $uid) {
        //将uid用户的报警通知地址加入到mysql中
        $adr = $this->addAlarmAdrMysql($dev_id, $uid);

        if(FALSE === $adr){
            return FALSE;
        } 
        
        //mysql添加成功，增加redis中对应设备报警通知地址
        $redis = new Redis();
        $select = $redis->whereRedis($dev_id);
        if(FALSE === $select){
            return false;
        }
        //切换数据库
        $redis->select($select);
        $addr = json_decode($redis->hget($dev_id, 'inform_addr'), true);
        $addr[$uid] = json_encode($adr);
        $redis->hset($dev_id, 'inform_addr', json_encode($addr));
        return true;
    }

}